<template>
  <div class="about">
    <h1>{{ id ? "编辑" : "新建" }}物品</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label="图标">
        <el-upload
          v-model="model.icon"
          class="avatar-uploader"
          action="http://localhost:3000/admin/api/upload"
          :headers="headers"
          :show-file-list="false"
          :on-success="afterUpload"
        >
          <img v-if="model.icon" :src="model.icon" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref, onBeforeMount } from "vue";
import { useRouter } from "vue-router";
import { postNewCategory, getDetail, putDetail } from "@/api";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
export default {
  props: {
    id: {},
  },
  components: {
    Plus,
  },
  setup(props) {
    var model = ref({});
    const router = useRouter();
    async function save() {
      let res = props.id
        ? await putDetail("items", props.id, model)
        : await postNewCategory("items", model);
      console.log(res);
      router.push("/items/list");
      ElMessage({
        message: "保存成功",
        type: "success",
      });
    }
    async function fetch() {
      const res = await getDetail("items", props.id);
      model.value = res.data;
    }
    function afterUpload(res) {
      console.log(res);
      model.value.icon = res.url;
      console.log(model.value.icon);
    }
    const headers = {
      Authorization: `Bearer ${localStorage.token}`,
    };
    onBeforeMount(() => {
      // 组件初次在页面渲染之前（创建阶段）唯一一次
      props.id && fetch();
    });
    return { model, save, afterUpload, headers };
  },
};
</script>

